package com.lm56.common.jcaptcha;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by Kelvin Yeung on 2016/6/12.
 */
public class JCaptchaUsernamePasswordAuthenticationFilter extends UsernamePasswordAuthenticationFilter {


    private static Logger logger = LoggerFactory.getLogger(JCaptchaUsernamePasswordAuthenticationFilter.class);

    public static final String SPRING_SECURITY_FORM_JCAPTCHA_KEY = "jcaptchaCode";
    private String jCaptcharCodeParameter = SPRING_SECURITY_FORM_JCAPTCHA_KEY;



    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {


        String checkCode  = obtainJCaptchaCode(request);
        try{
            //验证输入的验证码
            if(!JCaptcha.hasCaptcha(request, checkCode)){
                //验证不能过过，抛出异常
                throw new AuthenticationServiceException("验证码不正确");
            }

        }catch (RuntimeException e){
                logger.warn("验证码错误",e);
                e.printStackTrace();
                throw new AuthenticationServiceException("验证码错误");
        }

        return super.attemptAuthentication(request, response);
    }


    protected String obtainJCaptchaCode(HttpServletRequest request) {
        return request.getParameter(jCaptcharCodeParameter);
    }
}
